<template>
  <!-- 主播管理 -->
  <a-spin class="anchor-review" tip="加载中..." :spinning="isLoading">
    <!-- 筛选 -->
    <div class="filter">
      <div class="l search-box">
        <div>
          <span>业务经办人站点：</span>
          <a-select
            style="width:150px;margin-right:16px;"
            show-search
            :allowClear="true"
            placeholder="请选择站点"
            v-model="search.locationId"
            @change="handleByQueryCond"
            :filter-option="filterOption"
          >
            <a-select-option v-for="(item, index) in locationListData" :key="index + '-' + item.id" :value="item.id">{{ item.city }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>申请人：</span>
          <a-input-search style="width:150px;" type="text" placeholder="请输入姓名/工号" allowClear v-model="search.applyUser" @search="handleByQueryCond" />
          <!-- <a-select
            @search="getAllUserFun"
            v-model="search.applyUser"
            :showArrow="false"
            style="width:200px;"
            show-search
            :filter-option="false"
            allow-clear
            @change="handleByQueryCond"
            placeholder="申请人业务经办人姓名/工号"
          >
            <a-spin v-if="userLoading" slot="notFoundContent" size="small" />
            <a-select-option v-for="(item, index) in allUser" :key="index" :value="item.userId">{{ item.userName }}</a-select-option>
          </a-select> -->
        </div>
        <div>
          <span>请款类型：</span>
          <a-select style="width:150px;" placeholder="请选择状态" v-model="search.costType" @change="handleByQueryCond">
            <a-select-option v-for="item in applyStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>审批单号：</span>
          <a-input-search style="width:160px;" type="text" placeholder="请输入审批单号" allowClear v-model="search.approvalNo" @search="handleByQueryCond" />
        </div>
        <div>
          <span>状态：</span>
          <a-select style="width:160px;" placeholder="请选择状态" v-model="search.status" @change="handleByQueryCond">
            <a-select-option v-for="item in thisStatus" :key="item.value" :value="item.value">{{ item.name }}</a-select-option>
          </a-select>
        </div>
        <div>
          <span>达人昵称：</span>
          <a-input-search style="width:160px;" type="text" placeholder="请输入达人昵称" allowClear v-model="search.agentName" @search="handleByQueryCond" />
        </div>
        <div>
          <span>产品套餐ID：</span>
          <a-input-search style="width:160px;" type="text" placeholder="请输入产品套餐ID" allowClear v-model="search.productItemId" @search="handleByQueryCond" />
        </div>
        <div>
          <span>日期：</span>
          <a-range-picker @change="handleByQueryCond" v-model="search.selectDate" />
        </div>
      </div>

      <div class="r">
        <a-button type="primary" @click="aboutApply(1)" style="background:#1d6fe9">发起申请</a-button>
      </div>
    </div>

    <!-- 表格 -->
    <div class="main-body">
      <div class="remind-text">*提交申请后需要业务经办人所属站点的分总进行审批，非申请人所属站点分总哦～（财务要求）</div>
      <a-table :columns="tableColumns" :pagination="false" :data-source="agentShopList" :scroll="{ x: 900, y: tableHeight - 50 }" :rowKey="(r, i) => i.toString()">
        <!-- <template slot="applyUserName" slot-scope="text, record">
          <p>{{ record.applyUserName || '--' }}</p>
        </template> -->
        <!-- 状态 -->
        <template slot="transferStatus" slot-scope="text, record">
          <p>审批：{{ record.status }}</p>
          <p>转账：{{ record.transferStatus }}</p>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button type="link" @click="aboutApply(2, record.id)">详情</a-button>
        </template>
      </a-table>
    </div>

    <!-- 分页 -->
    <div class="paging-container">
      <a-pagination
        :pageSize="pagination.pageSize"
        v-model="pagination.pageIndex"
        :total="pagination.total"
        showQuickJumper
        showLessItems
        :showTotal="(total) => `共 ${total} 条`"
        style="margin: 10px auto;"
        @change="handlePageChange"
      />
    </div>
    <apply-talent v-model="isShowApplyModel" @callback="query()" :type="openType" :getInfo="postDetail" @onCancel="handleCancel"> </apply-talent>
  </a-spin>
</template>

<script>
import { agentShopList, getAllUserList, agentShopDetail, locationList } from '@/service'
import { safeDiv } from '@/util'
import debounce from 'lodash/debounce'
import applyTalent from './applyTalent'
import moment from 'moment'
export default {
  name: 'talentShop',
  data() {
    this.getAllUserFun = debounce(this.getAllUserFun, 800)
    return {
      // loading是否显示
      isLoading: false,
      userLoading: false,
      openType: 0, // 1 新增 2 详情
      allUser: [],
      pagination: {
        total: 0,
        pageIndex: 1,
        pageSize: 10
      },
      // table数据查询条件
      search: {
        status: '',
        costType: '',
        approvalNo: '',
        applyUser: undefined,
        selectDate: [],
        productItemId: '',
        locationId: undefined,
        agentName: ''
      },
      // 列表
      agentShopList: [],
      // 申请显隐
      isShowApplyModel: false,
      // 详情数据
      postDetail: {},
      // 站点列表
      locationListData: []
    }
  },

  components: {
    applyTalent
  },

  computed: {
    // table配置
    tableColumns() {
      return [
        { title: '审批单号', width: 240, dataIndex: 'approvalNo' },
        { title: '申请时间', width: 200, dataIndex: 'applyTime' },
        { title: '申请人', width: 240, dataIndex: 'applyUserName' },
        {
          title: '请款类型',
          width: 230,
          dataIndex: 'costType'
          // customRender: (text) => {
          //   switch (text) {
          //     case 1:
          //       return 'CPS + 一口价全款'
          //     case 2:
          //       return 'cps+一口价首款'
          //     case 3:
          //       return 'cps+一口价尾款'
          //     case 4:
          //       return '一口价全款'
          //     case 5:
          //       return '一口价首款'
          //     case 6:
          //       return '一口价尾款'
          //     case 7:
          //       return '其他'
          //     default:
          //       return '未知'
          //   }
          // }
        },
        { title: '业务经办人', width: 220, dataIndex: 'businessUserName' },
        { title: '达人昵称', width: 200, dataIndex: 'agentName' },
        {
          title: '金额',
          width: 200,
          dataIndex: 'money',
          customRender: (data) => {
            if (!data) return '￥0'
            return '￥' + safeDiv(data, 100)
          }
        },
        { title: '状态', width: 200, dataIndex: 'transferStatus', scopedSlots: { customRender: 'transferStatus' } },
        { title: '操作', fixed: 'right', width: 90, dataIndex: 'action', scopedSlots: { customRender: 'action' } }
      ]
    },

    // 状态
    // 状态
    applyStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: 'cps+一口价全款',
          value: 1
        },
        {
          name: 'cps+一口价首款',
          value: 2
        },
        {
          name: 'cps+一口价尾款',
          value: 3
        },
        {
          name: 'cps+一口价其他',
          value: 4
        },
        {
          name: '一口价全款',
          value: 5
        },
        {
          name: '一口价首款',
          value: 6
        },
        {
          name: '一口价尾款',
          value: 7
        },
        {
          name: '一口价其他',
          value: 8
        }
      ]
    },
    thisStatus() {
      return [
        {
          name: '全部',
          value: ''
        },
        {
          name: '已驳回',
          value: 2
        },
        {
          name: '已通过',
          value: 1
        },
        {
          name: '审核中',
          value: 0
        }
      ]
    }
  },

  methods: {
    rowKeyFn(record, index) {
      console.log(record)
      return record.id
    },
    /**
     * 通过条件查询
     * @returns {void}
     */
    handleByQueryCond() {
      this.pagination.pageIndex = 1
      this.query()
    },

    /**
     * 分页
     * @param {number} num 当前页码
     * @returns {void}
     */
    handlePageChange(num) {
      this.pagination.pageIndex = num
      this.query()
    },

    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },

    // 站点列表
    async getLocationList() {
      await locationList({ city: '' }).then((res = []) => {
        this.locationListData = res
      })
    },

    // 拿参数
    getParams() {
      const { pageIndex, pageSize } = this.pagination
      const { status, costType, approvalNo, applyUser, selectDate, productItemId, locationId, agentName } = this.search

      return {
        pageIndex,
        pageSize,
        status,
        costType,
        approvalNo,
        applyUser,
        productItemId,
        locationId,
        agentName,
        startDate: selectDate[0] ? moment(selectDate[0]).format('YYYY-MM-DD 00:00:00') : undefined,
        endDate: selectDate[1] ? moment(selectDate[1]).format('YYYY-MM-DD 23:59:59') : undefined
      }
    },
    // 设置搜索
    setSearch() {
      const { pageIndex, costType, approvalNo, applyUser, status, startDate, endDate, productItemId, locationId, agentName } = this.$route.query
      const queryLen = Object.keys(this.$route.query).length
      if (queryLen) {
        this.search = {
          ...this.search,
          pageIndex: pageIndex ? Number(pageIndex) : 1,
          status: status || '',
          costType: costType || '',
          approvalNo: approvalNo || '',
          applyUser: applyUser || '',
          productItemId: productItemId || '',
          locationId: locationId || '',
          agentName: agentName || '',
          selectDate: startDate && endDate ? [moment(Number(startDate)), moment(Number(endDate))] : []
        }
      }
    },
    // 初始化
    initQuery() {
      this.pagination.pageIndex = 1
      this.pagination.pageSize = 10
      this.setPath(this.getParams())
      this.query()
    },

    // 获取页面列表
    async query() {
      const res = await agentShopList(this.getParams())
      const { applyListData = [], total = 0 } = res || {}
      this.agentShopList = Object.freeze(applyListData) || []
      this.pagination.total = total || 0
      this.isLoading = false
    },
    // 储存搜索字段
    setPath(origin) {
      const { path } = this.$route
      const query = {}
      for (let key in origin) {
        if (origin[key]) query[key] = origin[key]
      }
      if (query.pageIndex <= 1) delete query.pageIndex
      delete query.pageSize
      this.$router
        .replace({
          path,
          query: {
            ...query
          }
        })
        .catch(() => {})
    },
    getAllUserFun(keywords) {
      return new Promise((resolve, reject) => {
        keywords = keywords.replace(/ /g, '')
        // if (!keywords) return reject(new Error('process'))
        this.userLoading = true
        getAllUserList({ keywords })
          .then((res = {}) => {
            const { records = [] } = res
            this.allUser = records
            resolve(res)
          })
          .catch(() => {
            return reject(new Error('接口出错'))
          })
          .finally(() => {
            this.userLoading = false
          })
      })
    },
    aboutApply(type = 0, id = '') {
      this.openType = type
      if (type === 2) {
        this.getDetail(id)
          .then(() => {
            this.isShowApplyModel = true
          })
          .catch(() => {
            this.isLoading = false
          })
      } else {
        this.isShowApplyModel = true
      }
    },
    handleCancel() {
      this.isShowApplyModel = false
    },
    getDetail(id = '') {
      return new Promise((resolve, reject) => {
        this.isLoading = true
        agentShopDetail({ id })
          .then((res = {}) => {
            this.postDetail = res || {}
            console.log(this.postDetail, res)
            resolve()
          })
          .finally(() => {
            this.isLoading = false
          })
          .catch(() => {
            this.isLoading = false
          })
      })
    }
  },

  mounted() {
    this.getLocationList()
    this.isLoading = true
    this.setSearch()
    this.query()
  },

  filters: {
    // 获取直播平台
    filApplyStatus(val) {
      switch (val) {
        case 0:
          return '审核中'
        case 1:
          return '已通过'
        case 2:
          return '已驳回'
        default:
          return '无'
      }
    },
    transStatus(val) {
      if (!val) return '无'
      return val === 0 ? '无' : '已完成'
    },
    // 处理分-元
    fenToYuan(val) {
      if (!val) return 0
      return (val / 100).toFixed(2)
    }
  }
}
</script>

<style lang="less" scoped>
p {
  margin: 0;
}
.anchor-review {
  padding: 16px;
}
/deep/ .ant-table-thead > tr:first-child > th:last-child {
  text-align: center;
}
// 主播信息弹窗
.anchor-info {
  /deep/ .ant-modal-footer {
    border-top: none;
    padding-bottom: 36px;
    text-align: center;
  }

  //  描述列表样式覆盖
  /deep/ .ant-descriptions-view {
    .ant-descriptions-item-label {
      color: #666666;
    }

    .ant-descriptions-item-content {
      color: #333;
      vertical-align: text-top;
    }
  }
}
.color-f55 {
  color: #f55f4e !important;
}
.search-box {
  display: flex;
  justify-content: flex-start;
  width: 100%;
  flex-wrap: wrap;
  > div {
    margin-right: 15px;
    margin-bottom: 5px;
  }
}
.remind-text {
  font-size: 12px;
  color: #e64242;
  margin: -10px 0 5px 0;
}
</style>
